import Flutter
import UIKit
import CoreBluetooth

public class FlutterBluetoothPrinterPlugin: NSObject, FlutterPlugin, CBCentralManagerDelegate, CBPeripheralDelegate {

    private var centralManager: CBCentralManager!
    private var targetPeripheral: CBPeripheral?
    private var flutterResult: FlutterResult?
    private var printData: Data?

    // 替换为你打印机的实际 BLE Service UUID
    private let printerServiceUUID = CBUUID(string: "0000FFF0-0000-1000-8000-00805F9B34FB")
    // 替换为你打印机的实际可写 Characteristic UUID
    private let writeCharacteristicUUID = CBUUID(string: "0000FFF1-0000-1000-8000-00805F9B34FB")

    public static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "flutter_bluetooth_printer", binaryMessenger: registrar.messenger())
        let instance = FlutterBluetoothPrinterPlugin()
        registrar.addMethodCallDelegate(instance, channel: channel)
    }

    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        if call.method == "printerStart" {
            guard let args = call.arguments as? [String: Any],
                  let data = args["data"] as? FlutterStandardTypedData else {
                result(["code": 0, "msg": "未获取到打印内容"])
                return
            }

            let byteArray = data.data
            self.printData = byteArray
            self.flutterResult = result
            // 初始化或检查蓝牙状态
            if centralManager == nil {
                centralManager = CBCentralManager(delegate: self, queue: nil)
            } else if centralManager.state == .poweredOn {
                startScanForPrinter()
            }

        } else if call.method == "printerOpenBluetooth" {
            if let settingsUrl = URL(string: UIApplication.openSettingsURLString) {
                UIApplication.shared.open(settingsUrl, completionHandler: nil)
            }

        } else if call.method == "printerOpenWifi" {
            if let settingsUrl = URL(string: UIApplication.openSettingsURLString) {
                UIApplication.shared.open(settingsUrl, completionHandler: nil)
            }
        } else {
            result(FlutterMethodNotImplemented)
        }
    }

    private func startScanForPrinter() {
        centralManager.scanForPeripherals(withServices: [printerServiceUUID], options: nil)
        DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
            self.centralManager.stopScan()
            if self.targetPeripheral == nil {
                self.flutterResult?([
                                        "code": 0,
                                        "msg": "未找到支持BLE的TSC打印机（请确认打印机已开启且支持BLE）"
                                    ])
                self.resetState()
            }
        }
    }

    public func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state != .poweredOn {
            flutterResult?([
                               "code": -1,
                               "msg": "蓝牙未开启，请在系统设置中启用蓝牙"
                           ])
            resetState()
        }
    }

    public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        // 可根据名称进一步过滤，例如包含 "TSC"
        if let name = peripheral.name, name.uppercased().contains("TSC") {
            centralManager.stopScan()
            targetPeripheral = peripheral
            targetPeripheral?.delegate = self
            centralManager.connect(peripheral, options: nil)
        }
    }

    public func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        peripheral.discoverServices([printerServiceUUID])
    }

    public func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
        flutterResult?([
                           "code": 0,
                           "msg": "连接打印机失败: \(error?.localizedDescription ?? "未知错误")"
                       ])
        resetState()
    }

    // MARK: - CBPeripheralDelegate

    public func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        guard let services = peripheral.services else { return }

        for service in services {
            if service.uuid == printerServiceUUID {
                peripheral.discoverCharacteristics([writeCharacteristicUUID], for: service)
                return
            }
        }

        // 未找到服务
        flutterResult?(["code": 0, "msg": "未找到打印机的服务"])
        centralManager.cancelPeripheralConnection(peripheral)
        resetState()
    }

    public func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        guard let characteristics = service.characteristics else { return }

        for characteristic in characteristics {
            if characteristic.uuid == writeCharacteristicUUID && characteristic.properties.contains(.write) {
                // 发送打印数据
                peripheral.writeValue(printData!, for: characteristic, type: .withResponse)
                return
            }
        }

        flutterResult?(["code": 0, "msg": "未找到可写的特征值"])
        centralManager.cancelPeripheralConnection(peripheral)
        resetState()
    }

    public func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
        if let error = error {
            flutterResult?(["code": 0, "msg": "写入失败: \(error.localizedDescription)"])
        } else {
            flutterResult?(["code": 1, "msg": "蓝牙打印成功"])
        }
        centralManager.cancelPeripheralConnection(peripheral)
        resetState()
    }

    private func resetState() {
        flutterResult = nil
        printData = nil
        targetPeripheral = nil
    }
}
